/* Created By Micha Sherman, google workshop 2012
 * 
 */

package com.sporteamws;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.appengine.utils.AeLoadingCenter;
import com.appengine.utils.GsonUtils;
import com.appengine.utils.SavingAndLoadingCenter;
import com.datatypes.User;
import com.facebook.android.Facebook;
import com.facebook.android.Login;
import com.google.gwt.dev.javac.Shared;
import com.gps.misc.ActivityCenter;
import com.gps.misc.GhostRecord;
import com.gps.track.GpsTrackingActivitySolo;
import com.gps.utilities.LocationBlank;

public class MainMenu extends Activity implements OnClickListener {

	// global variables
	public Facebook mFacebook = new Facebook(SharedPref.facebook_appID);

	ImageButton run = null;
	ImageButton coop = null;
	ImageButton ghost = null;
	ImageView profile_pic = null;
	TextView welcome = null;
	User user = null;

	boolean logout = false;

	String screenName;
	String native_package = "com.sporteamws.";
	String xml_package = "com.xml.test.";
	String facebook_package = "com.facebook.android.";
	String network_mode;

	ProgressBar picLoadingPB = null;
	LocationManager lm = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// setup content view
		setContentView(R.layout.main_menu);

		/**************/
		run = (ImageButton) findViewById(R.id.run);
		coop = (ImageButton) findViewById(R.id.coop);
		ghost = (ImageButton) findViewById(R.id.ghosts);
		profile_pic = (ImageView) findViewById(R.id.profilePic);
		welcome = (TextView) findViewById(R.id.welcomeText);
		picLoadingPB = (ProgressBar) findViewById(R.id.ProfilePicPB);

		/************/

		// load user from internal storage
		user = SavingAndLoadingCenter.loadUser(SharedPref.facebookID,
				MainMenu.this);

		// load profile pic on backround thread
		AeLoadingCenter.LoadProfilePic(SharedPref.facebookID, MainMenu.this,
				profile_pic, picLoadingPB);

		SavingAndLoadingCenter.loadSettings(this).setPrefInfo();

		if (user != null) {
			welcome.setText("Welcome " + user.GetFirstName() + " "
					+ user.GetLastName());
		}

		run.setOnClickListener(this);
		coop.setOnClickListener(this);
		ghost.setOnClickListener(this);

		// adapt to offline mode in case of no connection
		if (!SharedPref.GotNetworkConnection) {
			HandleOfflineMode();
		}
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5, SharedPref.lb);
	}

	// handles application when no internet connection found
	void HandleOfflineMode() {
		// make appropriate text views invisible
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add("settings").setIcon(R.drawable.settings);
		menu.add("sync").setIcon(android.R.drawable.ic_popup_sync);
		menu.add("logout").setIcon(R.drawable.logout_icon);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if (item.getTitle().equals("settings")) {
			Intent intent = new Intent(this, Options.class);
			SharedPref.onHome = false;
			startActivity(intent);
		} else if (item.getTitle().equals("sync")) {
			HandleSync();
		} else if (item.getTitle().equals("logout")) {
			HandleLogout();
		}
		return super.onOptionsItemSelected(item);
	}

	private void HandleSync() {
		// check if network connection is changed
		UpdateNetworkConnectivity();

		if (SharedPref.GotNetworkConnection)
			AeLoadingCenter.LoadAEuser(SharedPref.facebookID, MainMenu.this);
		else
			showAlertDialog("can not sync with server without internet connection");
	}

	private void HandleLogout() {
		if (SharedPref.GotNetworkConnection)
			ExecuteLogout();
		else
			showAlertDialog("can not logout without internet connection");
	}

	void ExecuteLogout() {

		// check if network connection is changed
		UpdateNetworkConnectivity();
		SharedPref.FacebookLogout = true;
		SharedPref.lastUpdate = 0;
		SavingAndLoadingCenter.deleteMyImage(user.GetFacebookID(), this);
		SavingAndLoadingCenter
				.deleteFriendsImages(
						SavingAndLoadingCenter.loadFriendsZone(
								user.GetFacebookID(), this).getFriends(), this);
		SavingAndLoadingCenter.deleteAll(user.GetFacebookID(), this);
		Intent intent = new Intent(MainMenu.this, Login.class);
		startActivity(intent);
		this.finish();
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		Window window = getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (!this.isFinishing() && SharedPref.onHome){
			lm.removeUpdates(SharedPref.lb);
		}
	//	if (logout)
	//		finish();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		SavingAndLoadingCenter.loadUser(SharedPref.facebookID, this);
		if (SharedPref.onHome){
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5, SharedPref.lb);
		}
		else
			SharedPref.onHome = true;

	}

	@Override
	public void onBackPressed() {
		SavingAndLoadingCenter.deleteMyImage(user.GetFacebookID(), this);
		SavingAndLoadingCenter
				.deleteFriendsImages(
						SavingAndLoadingCenter.loadFriendsZone(
								user.GetFacebookID(), this).getFriends(), this);

		lm.removeUpdates(SharedPref.lb);
		super.onBackPressed();
	}

	@SuppressWarnings("deprecation")
	private void showAlertDialog(String msg) {
		final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		// alertDialog.setTitle("Houston, We've Got a Problem");
		alertDialog.setMessage(msg);
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();
			}
		});

		alertDialog.setIcon(R.drawable.alert);
		alertDialog.show();
	}

	private void UpdateNetworkConnectivity() {
		try {
			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo activeNetworkInfo = connectivityManager
					.getActiveNetworkInfo();

			if (activeNetworkInfo == null) {
				SharedPref.GotNetworkConnection = false;
				return;
			}

			NetworkInfo i = connectivityManager.getActiveNetworkInfo();
			if (i == null) {
				SharedPref.GotNetworkConnection = false;
				return;
			}
			if (!i.isConnected() || !i.isAvailable()) {
				SharedPref.GotNetworkConnection = false;
				return;
			}

			SharedPref.GotNetworkConnection = true;
		} catch (Exception e) {
			SharedPref.GotNetworkConnection = false;
			Log.e("error on update network connectivity", e.toString());
		}

	}

	@Override
	public void onClick(View v) {
		if (v.getId() == run.getId()) {
			Intent intent = new Intent(this, GpsTrackingActivitySolo.class);
			Bundle bundle = new Bundle();
			bundle.putBoolean("SOLO", true);
			String usrStr = GsonUtils.ConvertUserToGsonString(user);
			bundle.putString("USER", usrStr);
			intent.putExtras(bundle);
			SharedPref.onHome = false;
			startActivity(intent);
		} else if (v.getId() == coop.getId()) {
			Intent intent = new Intent(this, ActivityCenter.class);
			Bundle bundle = new Bundle();
			String usrStr = GsonUtils.ConvertUserToGsonString(user);
			bundle.putString("USER", usrStr);
			intent.putExtras(bundle);	
			SharedPref.onHome = false;
			AeLoadingCenter.LoadActivities(user.GetFacebookID(), intent, this);
		} else {
			Intent intent = new Intent(this, GhostRecord.class);
			Bundle bundle = new Bundle();
			String usrStr = GsonUtils.ConvertUserToGsonString(user);
			bundle.putString("USER", usrStr);
			intent.putExtras(bundle);
			SharedPref.onHome = false;
			AeLoadingCenter.LoadTracks(user.GetFacebookID(), intent, this);
		}

	}

}